﻿#region

using System;
using System.Diagnostics;
using System.IO;

#endregion


namespace OMS.Ice.T4Generator
{
    // Base class for all generator classes.
    public abstract class T4Generator
    {
        private TextWriter Output { get; set; }

        public void Generate( TextWriter output )
        {
            Output = output;
            Generate();
        }

        public abstract void Generate();

        //[DebuggerStepThrough]
        protected void Write( string text )
        {
            // The template may be generated for a non Windows platform. So we have to consider the different usage of line breaks.
            // CR+LF: Microsoft Windows, DEC TOPS-10, RT-11 and most other early non-Unix and non-IBM OSes, CP/M, MP/M, DOS (MS-DOS, PC-DOS, etc.), Atari TOS, OS/2, Symbian OS, Palm OS
            // LF+CR: Acorn BBC and RISC OS spooled text output.
            // LF   : Multics, Unix and Unix-like systems (GNU/Linux, Mac OS X, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS and others.
            // CR   : Commodore 8-bit machines, Acorn BBC, TRS-80, Apple II family, Mac OS up to version 9 and OS-9

            //  LF+CR will be interpreted as to lines by the parser. The first line ends with LF. The second line contains nothing but CR.
            // That's why we don't need to test for LF+CR.
            Func<string> textToWrite;
            if (text.EndsWith(@"\r\n"))
                textToWrite = () => text.Remove( text.Length - 4 ) + "\r\n";
            else if (text.EndsWith(@"\n"))
                textToWrite = () => text.Remove(text.Length - 2) + "\n";
            else if (text.EndsWith(@"\r"))
                textToWrite = () => text.Remove(text.Length - 2) + "\r";
            else
                textToWrite = () => text;

            Output.Write(textToWrite());
        }

        [DebuggerStepThrough]
        protected void Write( object value )
        {
            Write( value.ToString() );
        }
    }
}